# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : trigger_type_view.py
# Time       ：2023/11/2 15:16
# Author     ：YangYong
# version    ：python 3.10
# Description：启动方式对比
"""
from flask_restx import Resource, fields
from sqlalchemy import func, case

from apis.data_screen import data_screen_ns
from apis.data_screen.schema.trigger_type_schema import TriggerTypeSchema
from apis.orderlines.models import ProcessInstance
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel

trigger_type = {
    'schedule': fields.String(description='定时分类'),
    'trigger': fields.Float(description='触发占比')
}

trigger_type_marshal = MarshalModel('trigger_type', data_screen_ns)


class TriggerTypeView(Resource):
    url = '/trigger_type'

    def __init__(self, *args, **kwargs):
        super(TriggerTypeView, self).__init__(*args, **kwargs)
        self.total = 0
        self.schedule = 0

    @handle_api_error()
    @data_screen_ns.doc(description='启动方式对比')
    @data_screen_ns.marshal_with(trigger_type_marshal.detail_response(trigger_type, False))
    def get(self):
        """启动方式对比"""
        objs = db.session.query(
            func.sum(case(
                (ProcessInstance.run_type == 'schedule', 1),
                (ProcessInstance.run_type == 'trigger', 1),
            )
            ).label('value'),
            case(
                (ProcessInstance.run_type == 'schedule', '定时启动'),
                (ProcessInstance.run_type == 'trigger', '手动触发'),
            ).label('name')
        ).filter(ProcessInstance.active == 1).group_by('name').all()
        info = TriggerTypeSchema().dump(objs, many=True)
        for item in info:
            self.total = self.total + item.get('value') or 0

        for item in info:
            if item.get('name') == '定时启动':
                schedule_total = item.get('value')
                self.schedule = round(schedule_total / self.total, 2)

        return generate_response(
            {
                'schedule': self.schedule,
                'trigger': round((1 - self.schedule), 2)
            }
        )
